package com.platform.usercenter.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.platform.basicdata.api.remote.RemoteBasicdataService;
import com.platform.basicdata.api.remote.vo.DicAirportLocal;
import com.platform.common.core.constant.CacheConstants;
import com.platform.common.core.constant.HttpStatus;
import com.platform.common.core.constant.SecurityConstants;
import com.platform.common.core.constant.UserConstants;
import com.platform.common.core.domain.R;
import com.platform.common.core.domain.entity.SysRole;
import com.platform.common.core.domain.entity.SysUser;
import com.platform.common.core.domain.entity.SysUserAirInfo;
import com.platform.common.core.domain.model.LoginUser;
import com.platform.common.core.domain.model.SysUserVo;
import com.platform.common.core.enums.UserManagerEnum;
import com.platform.common.core.exception.ServiceException;
import com.platform.common.core.utils.DateUtils;
import com.platform.common.core.utils.PageUtils;
import com.platform.common.core.utils.SpringUtils;
import com.platform.common.core.utils.StringUtils;
import com.platform.common.core.utils.bean.BeanValidators;
import com.platform.common.core.web.page.TableDataInfo;
import com.platform.common.datascope.annotation.DataScope;
import com.platform.common.redis.service.RedisService;
import com.platform.common.security.utils.SecurityUtils;
import com.platform.constants.SysUserConstants;
import com.platform.usercenter.domain.*;
import com.platform.usercenter.domain.dto.*;
import com.platform.usercenter.domain.request.GetUserRoleFunctionRequest;
import com.platform.usercenter.domain.vo.*;
import com.platform.usercenter.mapper.*;
import com.platform.usercenter.service.ISysModelRoleFunctionService;
import com.platform.usercenter.service.ISysPermissionService;
import com.platform.usercenter.service.ISysUserCommonService;
import com.platform.usercenter.service.ISysUserService;
import com.platform.usercenter.utils.TreeAdapterUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 用户 业务层处理
 *
 * @author
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private SysRoleMapper roleMapper;

    @Resource
    private SysPostMapper postMapper;

    @Resource
    private SysUserRoleMapper userRoleMapper;

    @Resource
    private SysUserPostMapper userPostMapper;

    @Resource
    protected Validator validator;

    @Resource
    private SysUserDeptMapper userDeptMapper;

    @Resource
    private SysUserAirportMapper userAirportMapper;

    @Resource
    private SysDeptMapper userdeptMapper;

    @Resource
    private ISysPermissionService permissionService;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private RemoteBasicdataService remoteBasicdataService;

    @Resource
    private RedisService redisService;

    @Resource
    private SysDeptMapper deptMapper;

    @Resource
    private SysOrgDeptUserMapper orgDeptUserMapper;

    @Resource
    private SysOrganizationAdministratorMapper administratorMapper;

    @Resource
    private SysOrgDeptUserMapper sysOrgDeptUserMapper;

    @Resource
    private SysOrganizationMapper sysOrganizationMapper;

    @Resource
    private SysOrganizationRelationMapper sysOrganizationRelationMapper;

    @Resource
    private SysOrganizationDeptMapper sysOrganizationDeptMapper;

    @Resource
    private SysDeptPostMapper sysDeptPostMapper;

    @Resource
    private ISysUserCommonService sysUserCommonService;

    //散货主
    protected static final String AIR_PERSONAL_CODE = "airPersonal";
    //航发公司
    protected static final String AIRLINE_CODE = "airline";
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private ISysModelRoleFunctionService sysModelRoleFunctionService;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        List<SysUser> sysUsers = userMapper.selectUserList(user);
        for (SysUser sysUser : sysUsers) {
            //sysUser.setLock(isLockUser(sysUser.getUserName()));
        }
        return sysUsers;
    }

    @Override
    public TableDataInfo getUserInfoById(SysUserVO user) {
        // 处理部门子节点id
        if (ObjectUtil.isNotEmpty(user.getDeptId())) {
            Set<Long> deptIds = new HashSet<>();
            deptIds.add(user.getDeptId());
            SysOrganizationDept organizationDept = new SysOrganizationDept();
            organizationDept.setOrgId(user.getOrgId());
            organizationDept.setDeptId(user.getDeptId());
            List<SysOrganizationDept> deptList = sysOrganizationDeptMapper.selectDeptListByParentId(organizationDept);
            if (CollectionUtil.isNotEmpty(deptList)) {
                deptIds.addAll(deptList.stream().map(SysOrganizationDept::getDeptId).collect(Collectors.toSet()));
                user.setDeptIds(new ArrayList<>(deptIds));
            }
            user.setDeptId(null);
        }
        startPage();
        return getDataTable(userMapper.getUserInfoById(user));
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageUtils.startPage();
    }


    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    @Override
    public List<SysUserVO> selectUserVOList(SysUserVO user) {
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        if (sysUserCommonService.isAdmin(userId)) {
            return userMapper.selectUserVOList(user);
        } else {
            Long orgId = SecurityUtils.getLoginUser().getOrgId();
            user.setOrgId(orgId);
            return userMapper.selectUserVOListByUserId(user);
        }
    }

    /**
     * 递归设置部门树中的orgDept字段
     * @param deptVOList 部门列表
     * @param orgId 组织ID
     */
    private void setOrgDeptForDeptTree(List<SysOrganizationDeptVO> deptVOList, Long orgId) {
        if (CollectionUtil.isNotEmpty(deptVOList)) {
            for (SysOrganizationDeptVO deptVO : deptVOList) {
                deptVO.setOrgDept(orgId + "_" + deptVO.getDeptId());
                if (CollectionUtil.isNotEmpty(deptVO.getChildren())) {
                    setOrgDeptForDeptTree(deptVO.getChildren(), orgId);
                }
            }
        }
    }

    @Override
    public List<SysUserOrgTreeVO> getOrgTree() {
        List<SysUserOrgTreeVO> userOrgTreeVOS = new ArrayList<>();
        // 查询组织
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        Long orgId = SecurityUtils.getLoginUser().getOrgId();
        SysOrganization organization = new SysOrganization();
        if (!sysUserCommonService.isAdmin(userId)) {
            organization.setOrgId(orgId);
        }
        List<SysOrganizationVO> organizationVOS = sysOrganizationMapper.listTree(organization);
        if (CollectionUtil.isNotEmpty(organizationVOS)) {
            for (SysOrganizationVO vo : organizationVOS) {
                SysUserOrgTreeVO userOrgTreeVO = new SysUserOrgTreeVO();
                userOrgTreeVO.setParentId(vo.getParentId());
                userOrgTreeVO.setOrgId(vo.getOrgId());
                userOrgTreeVO.setOrgName(vo.getOrgName());
                // 查询部门
                SysOrganizationDept organizationDept = new SysOrganizationDept();
                organizationDept.setOrgId(vo.getOrgId());
                organizationDept.setIsDelete(SysUserConstants.N);
                List<SysOrganizationDept> depts = sysOrganizationDeptMapper.selectSysOrganizationDeptList(organizationDept);
                // 查询岗位
                Map<Long, List<SysDeptPost>> listMap = new HashMap<>();
                SysDeptPost deptPostQuery = new SysDeptPost();
                deptPostQuery.setOrgId(vo.getOrgId());
                deptPostQuery.setIsDelete(SysUserConstants.N);
                List<SysDeptPost> deptPosts = sysDeptPostMapper.selectSysDeptPostList(deptPostQuery);
                if (CollectionUtil.isNotEmpty(deptPosts)) {
                    listMap = deptPosts.stream().collect(Collectors.groupingBy(SysDeptPost::getDeptId));
                }
                if (CollectionUtil.isNotEmpty(depts)) {
                    for (SysOrganizationDept dept : depts) {
                        SysDeptPost deptPost = new SysDeptPost();
                        deptPost.setDeptId(dept.getDeptId());
                        deptPost.setOrgId(vo.getOrgId());
                        List<SysDeptPost> sysDeptPosts = listMap.get(dept.getDeptId());
                        if (CollectionUtil.isNotEmpty(sysDeptPosts)) {
                            dept.setSysDeptPosts(sysDeptPosts);
                        }

                    }
                    // 组装部门树
                    depts = TreeAdapterUtil.buildTree(depts, SysOrganizationDept.class, null);
                    userOrgTreeVO.setSysOrganizationDepts(depts);
                }
                userOrgTreeVOS.add(userOrgTreeVO);
            }
            // 组装组织树
            userOrgTreeVOS = TreeAdapterUtil.buildTree(userOrgTreeVOS, SysUserOrgTreeVO.class, null);

        }
        return userOrgTreeVOS;
    }

    @Override
    public List<SysOrgDeptTreeVO> orgDeptTree() {

        List<SysOrgDeptTreeVO> userOrgTreeVOS = new ArrayList<>();
        // 查询组织
        SysOrganization organization = new SysOrganization();
        List<SysOrganizationVO> organizationVOS = sysOrganizationMapper.listTree(organization);
        if (CollectionUtil.isNotEmpty(organizationVOS)) {
            for (SysOrganizationVO vo : organizationVOS) {

                SysOrgDeptTreeVO userOrgTreeVO = new SysOrgDeptTreeVO();
                userOrgTreeVO.setOrgId(vo.getOrgId());
                userOrgTreeVO.setOrgName(vo.getOrgName());
                // 查询部门
                SysOrganizationDept organizationDept = new SysOrganizationDept();
                organizationDept.setOrgId(vo.getOrgId());
                organizationDept.setIsDelete(SysUserConstants.N);
                List<SysOrganizationDept> depts = sysOrganizationDeptMapper.selectSysOrganizationDeptList(organizationDept);

                List<SysOrganizationDeptVO> deptVOList = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(depts)) {
                    for (SysOrganizationDept dept : depts) {
                        SysOrganizationDeptVO deptVO = new SysOrganizationDeptVO();
                        BeanUtils.copyProperties(dept, deptVO);
                        deptVO.setOrgDept(vo.getOrgId() + "_" + dept.getDeptId());
                        deptVOList.add(deptVO);
                    }
                    // 组装部门树
                    deptVOList = TreeAdapterUtil.buildTree(deptVOList, SysOrganizationDeptVO.class, null);
                    // 为所有层级的部门设置orgDept字段
                    setOrgDeptForDeptTree(deptVOList, vo.getOrgId());
                    userOrgTreeVO.setSysOrganizationDepts(deptVOList);
                }
                userOrgTreeVOS.add(userOrgTreeVO);
            }
        }
        return userOrgTreeVOS;
    }


    @Override
    public List<SysOrgDeptTreeVO> orgTreeDeptTree() {

        List<SysOrgDeptTreeVO> userOrgTreeVOS = new ArrayList<>();
        // 查询组织
        SysOrganization organization = new SysOrganization();
        List<SysOrganizationVO> organizationVOS = sysOrganizationMapper.listTree(organization);
        if (CollectionUtil.isNotEmpty(organizationVOS)) {
            for (SysOrganizationVO vo : organizationVOS) {

                SysOrgDeptTreeVO userOrgTreeVO = new SysOrgDeptTreeVO();
                userOrgTreeVO.setOrgId(vo.getOrgId());
                userOrgTreeVO.setOrgName(vo.getOrgName());
                userOrgTreeVO.setParentId( vo.getParentId() );
                // 查询部门
                SysOrganizationDept organizationDept = new SysOrganizationDept();
                organizationDept.setOrgId(vo.getOrgId());
                organizationDept.setIsDelete(SysUserConstants.N);
                List<SysOrganizationDept> depts = sysOrganizationDeptMapper.selectSysOrganizationDeptList(organizationDept);

                List<SysOrganizationDeptVO> deptVOList = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(depts)) {
                    for (SysOrganizationDept dept : depts) {
                        SysOrganizationDeptVO deptVO = new SysOrganizationDeptVO();
                        BeanUtils.copyProperties(dept, deptVO);
                        deptVO.setOrgDept(vo.getOrgId() + "_" + dept.getDeptId());
                        deptVOList.add(deptVO);
                    }
                    // 组装部门树
                    deptVOList = TreeAdapterUtil.buildTree(deptVOList, SysOrganizationDeptVO.class, null);
                    // 为所有层级的部门设置orgDept字段
                    setOrgDeptForDeptTree(deptVOList, vo.getOrgId());
                    userOrgTreeVO.setSysOrganizationDepts(deptVOList);
                }
                userOrgTreeVOS.add(userOrgTreeVO);
            }
            // 组装组织树
            userOrgTreeVOS = TreeAdapterUtil.buildTree(userOrgTreeVOS, SysOrgDeptTreeVO.class, null);
        }
        return userOrgTreeVOS;
    }

    @Override
    public List<SysOrgDeptTreeVO> approvalOrgDeptTree() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (Objects.isNull(loginUser)) {
            throw new ServiceException("用户未登录或登录过期,请重新登录");
        }
        Long orgId = SecurityUtils.getLoginUser().getOrgId();
        if (Objects.isNull(orgId)) {
            throw new ServiceException("当前用户没有配置归属组织请检查");
        }
        List<SysOrgDeptTreeVO> userOrgTreeVOS = new ArrayList<>();
        List<Long> orgIds = Lists.newArrayList(orgId);
        List<Long> actualSubordinateOrgIds = sysOrganizationRelationMapper.selectActualSubordinate(orgIds);
        List<Long> relationSubordinateOrgIds = sysOrganizationRelationMapper.selectRelationSubordinate(orgIds);
        orgIds.addAll(actualSubordinateOrgIds);
        orgIds.addAll(relationSubordinateOrgIds);
        if (!CollectionUtils.isEmpty(relationSubordinateOrgIds)) {
            List<Long> otherSubordinateOrgIds = sysOrganizationRelationMapper.selectActualSubordinate(orgIds);
            orgIds.addAll(otherSubordinateOrgIds);
        }
        // 查询组织
        SysOrganization organization = new SysOrganization();
        organization.setOrgIds(orgIds);
        List<SysOrganizationVO> organizationVOS = sysOrganizationMapper.listApprovalOrgByIds(organization);
        if (CollectionUtil.isNotEmpty(organizationVOS)) {
            for (SysOrganizationVO vo : organizationVOS) {

                SysOrgDeptTreeVO userOrgTreeVO = new SysOrgDeptTreeVO();
                userOrgTreeVO.setOrgId(vo.getOrgId());
                userOrgTreeVO.setOrgName(vo.getOrgName());
                // 查询部门
                SysOrganizationDept organizationDept = new SysOrganizationDept();
                organizationDept.setOrgId(vo.getOrgId());
                organizationDept.setIsDelete(SysUserConstants.N);
                List<SysOrganizationDept> depts = sysOrganizationDeptMapper.selectSysOrganizationDeptList(organizationDept);

                List<SysOrganizationDeptVO> deptVOList = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(depts)) {
                    for (SysOrganizationDept dept : depts) {
                        SysOrganizationDeptVO deptVO = new SysOrganizationDeptVO();
                        BeanUtils.copyProperties(dept, deptVO);
                        deptVOList.add(deptVO);
                    }
                    // 组装部门树
                    deptVOList = TreeAdapterUtil.buildTree(deptVOList, SysOrganizationDeptVO.class, null);
                    userOrgTreeVO.setSysOrganizationDepts(deptVOList);
                }
                userOrgTreeVOS.add(userOrgTreeVO);
            }
        }
        return userOrgTreeVOS;
    }


    @Override
    public List<SysOrgDeptTreeVO> approvalOrgNonDeptTree() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (Objects.isNull(loginUser)) {
            throw new ServiceException("用户未登录或登录过期,请重新登录");
        }
        Long orgId = SecurityUtils.getLoginUser().getOrgId();
        if (Objects.isNull(orgId)) {
            throw new ServiceException("当前用户没有配置归属组织请检查");
        }
        List<SysOrgDeptTreeVO> userOrgTreeVOS = new ArrayList<>();
        List<Long> orgIds = Lists.newArrayList(orgId);
        List<Long> actualSubordinateOrgIds = sysOrganizationRelationMapper.selectActualSubordinate(orgIds);
        List<Long> relationSubordinateOrgIds = sysOrganizationRelationMapper.selectRelationSubordinate(orgIds);
        orgIds.addAll(actualSubordinateOrgIds);
        orgIds.addAll(relationSubordinateOrgIds);
        if (!CollectionUtils.isEmpty(relationSubordinateOrgIds)) {
            List<Long> otherSubordinateOrgIds = sysOrganizationRelationMapper.selectActualSubordinate(orgIds);
            orgIds.addAll(otherSubordinateOrgIds);
        }
        // 查询组织
        SysOrganization organization = new SysOrganization();
        organization.setOrgIds(orgIds);
        List<SysOrganizationVO> organizationVOS = sysOrganizationMapper.listApprovalOrgByIds(organization);
        if (CollectionUtil.isNotEmpty(organizationVOS)) {
            for (SysOrganizationVO vo : organizationVOS) {

                SysOrgDeptTreeVO userOrgTreeVO = new SysOrgDeptTreeVO();
                userOrgTreeVO.setOrgId(vo.getOrgId());
                userOrgTreeVO.setOrgName(vo.getOrgName());
                userOrgTreeVOS.add(userOrgTreeVO);
            }
        }
        return userOrgTreeVOS;
    }


    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> noPermissionList(SysUser user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        SysUser sysUser = userMapper.selectUserByUserName(userName);
        setDeptIds(sysUser);
        setRoles(sysUser);
        return sysUser;
    }

    @Override
    public void setRoles(SysUser sysUser) {
        List<SysRole> roles = sysUserRoleMapper.selectUserRole(sysUser);
        if (CollectionUtil.isNotEmpty(roles)) {
            sysUser.setRoles(roles);
        }
    }

    @Override
    public List<SysRole> getCurrentOrgUserRoles(SysUser sysUser) {
        return sysUserRoleMapper.selectUserRole(sysUser);
    }

    /**
     * 通过用户手机号查询用户
     *
     * @param phone 手机号
     * @return
     */
    @Override
    public SysUser selectByPhonenumber(String phone) {

        return userMapper.selectByPhonenumber(phone);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        SysUser sysUser = userMapper.selectUserById(userId);
        setRoles(sysUser);
        return sysUser;
    }

    @Override
    public List<SysRole> getRoleByUser(Long userId, Long orgId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setOrgId(orgId);
        List<SysRole> roles = sysUserRoleMapper.selectUserRole(sysUser);
        return roles;
    }

    @Override
    public List<SysOrgRoleVo> getOrgRoleByUserUser(Long orgId) {
        List<SysOrgRoleVo> sysOrgRoleVos = new ArrayList<>();
        List<SysOrgRoleValDTO> roleDTOS = sysUserRoleMapper.getOrgRoleByUserOrgId(orgId);
        if (CollectionUtil.isNotEmpty(roleDTOS)) {
            Map<Long, String> orgMap = new HashMap<>();
            for (SysOrgRoleValDTO roleValDTO : roleDTOS) {
                orgMap.put(roleValDTO.getOrgId(), roleValDTO.getOrgName());
            }
            Map<Long, List<SysOrgRoleValDTO>> orgRoleMap = roleDTOS.stream().collect(Collectors.groupingBy(SysOrgRoleValDTO::getOrgId));
            for (Map.Entry<Long, List<SysOrgRoleValDTO>> entry : orgRoleMap.entrySet()) {
                SysOrgRoleVo orgRoleVo = new SysOrgRoleVo();
                List<SysOrgRoleValDTO> value = entry.getValue();
                orgRoleVo.setLabel(orgMap.get(entry.getKey()));
                List<SelectOptionDTO> options = new ArrayList<>();
                for (SysOrgRoleValDTO roleDTO : value) {
                    SelectOptionDTO optionDTO = new SelectOptionDTO();
                    optionDTO.setLabel(roleDTO.getRoleName());
                    optionDTO.setValue(String.valueOf(roleDTO.getRoleId()));
                    options.add(optionDTO);
                }
                orgRoleVo.setOptions(options);
                sysOrgRoleVos.add(orgRoleVo);
            }
        }
        return sysOrgRoleVos;
    }

    @Override
    public SysUserVo getUserInfo(Long userId) {
        SysUserVo sysUserVo = new SysUserVo();
        SysUser sysUser = userMapper.selectUserById(userId);
        BeanUtils.copyProperties(sysUser, sysUserVo);
        List<SysUserAirport> sysUserAirports = userAirportMapper.selectSysUserAirportByUserId(userId);
        List<SysUserAirInfo> airports = new ArrayList<>();
        for (SysUserAirport sysUserAirport : sysUserAirports) {
            SysUserAirInfo airInfo = new SysUserAirInfo();
            BeanUtils.copyProperties(sysUserAirport, airInfo);
            airports.add(airInfo);
        }
        sysUserVo.setAirCodes(airports);
        return sysUserVo;
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
//        insertUserPost(user);
        // 新增用户与角色管理
//        insertUserRole(user);
        return rows;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int joinOrg(SysUserDTO user) {
        List<SysUserRole> sysUserRoles = new ArrayList<>();
        List<SysOrgDeptUser> orgDeptUsers = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(user.getUserIds())) {
            for (Long userId : user.getUserIds()) {

                // 删除改用户下组织、部门、岗位信息
                orgDeptUserMapper.deleteSysOrgDeptUserByUserId(userId);
                // 删除改用户下角色信息
                userRoleMapper.deleteUserRoleByUserId(userId);

                if (CollectionUtil.isNotEmpty(user.getInfoList())) {
                    for (SysUserInfoDTO dto : user.getInfoList()) {
                        // 判断是否默认组织
                        if (StringUtils.isNotEmpty(dto.getIsDefault()) && SysUserConstants.Y.equals(dto.getIsDefault())) {
                            // 更新用户主表默认组织信息
                            SysUser sysUser = new SysUser();
                            sysUser.setUserId(userId);
                            sysUser.setOrgId(dto.getOrgId());
                            sysUser.setUpdateBy(SecurityUtils.getUsername());
                            sysUser.setUpdateTime(DateUtils.getNowDate());
                            userMapper.updateUser(sysUser);
                        }
                        for (SysDeptPostVO deptPostVO : dto.getDeptPostList()) {
                            // 新增用户组织-部门-岗位
                            if (ObjectUtil.isNotEmpty(deptPostVO.getPostIds())) {
                                for (Long postId : deptPostVO.getPostIds()) {
                                    SysOrgDeptUser orgDeptUser = new SysOrgDeptUser();
                                    orgDeptUser.setUserId(userId);
                                    orgDeptUser.setOrgId(dto.getOrgId());
                                    orgDeptUser.setDeptId(deptPostVO.getDeptId());
                                    orgDeptUser.setPostId(postId);
                                    orgDeptUser.setIsDelete(SysUserConstants.N);
                                    orgDeptUser.setCreateBy(SecurityUtils.getUsername());
                                    orgDeptUser.setCreateTime(new Date());
                                    orgDeptUsers.add(orgDeptUser);
                                }
                            } else {
                                SysOrgDeptUser orgDeptUser = new SysOrgDeptUser();
                                orgDeptUser.setUserId(userId);
                                orgDeptUser.setOrgId(dto.getOrgId());
                                orgDeptUser.setDeptId(deptPostVO.getDeptId());
                                orgDeptUser.setIsDelete(SysUserConstants.N);
                                orgDeptUser.setCreateBy(SecurityUtils.getUsername());
                                orgDeptUser.setCreateTime(new Date());
                                orgDeptUsers.add(orgDeptUser);
                            }
                        }
                        // 新增用户-角色
                        for (Long roleId : dto.getRoleIds()) {
                            SysUserRole userRole = new SysUserRole();
                            userRole.setOrgId(dto.getOrgId());
                            userRole.setIsDelete(SysUserConstants.N);
                            userRole.setUserId(userId);
                            userRole.setRoleId(roleId);
                            userRole.setCreateBy(SecurityUtils.getUsername());
                            userRole.setCreateTime(new Date());
                            sysUserRoles.add(userRole);
                        }
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(orgDeptUsers)) {
                orgDeptUserMapper.batchOrgDept(orgDeptUsers);
            }
            if (CollectionUtil.isNotEmpty(sysUserRoles)) {
                userRoleMapper.batchUserRole(sysUserRoles);
            }
        }
        return 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addOrgUser(SysUserDTO user) {
        int rows = userMapper.insertUser(user);
        if (rows > 0) {
            Long userId = user.getUserId();
            List<SysUserRole> sysUserRoles = new ArrayList<>();
            List<SysOrgDeptUser> orgDeptUsers = new ArrayList<>();
            // 删除改用户下组织、部门、岗位信息
            orgDeptUserMapper.deleteSysOrgDeptUserByUserId(userId);
            // 删除改用户下角色信息
            userRoleMapper.deleteUserRoleByUserId(userId);

            if (CollectionUtil.isNotEmpty(user.getInfoList())) {
                for (SysUserInfoDTO dto : user.getInfoList()) {
                    // 判断是否默认组织
                    if (StringUtils.isNotEmpty(dto.getIsDefault()) && SysUserConstants.Y.equals(dto.getIsDefault())) {
                        // 更新用户主表默认组织信息
                        SysUser sysUser = new SysUser();
                        sysUser.setUserId(userId);
                        sysUser.setOrgId(dto.getOrgId());
                        sysUser.setUpdateBy(SecurityUtils.getUsername());
                        sysUser.setUpdateTime(DateUtils.getNowDate());
                        userMapper.updateUser(sysUser);
                    }
                    for (SysDeptPostVO deptPostVO : dto.getDeptPostList()) {
                        // 新增用户组织-部门-岗位
                        if (ObjectUtil.isNotEmpty(deptPostVO.getPostIds())) {
                            for (Long postId : deptPostVO.getPostIds()) {
                                SysOrgDeptUser orgDeptUser = new SysOrgDeptUser();
                                orgDeptUser.setUserId(userId);
                                orgDeptUser.setOrgId(dto.getOrgId());
                                orgDeptUser.setDeptId(deptPostVO.getDeptId());
                                orgDeptUser.setPostId(postId);
                                orgDeptUser.setIsDelete(SysUserConstants.N);
                                orgDeptUser.setCreateBy(SecurityUtils.getUsername());
                                orgDeptUser.setCreateTime(new Date());
                                orgDeptUsers.add(orgDeptUser);
                            }
                        } else {
                            SysOrgDeptUser orgDeptUser = new SysOrgDeptUser();
                            orgDeptUser.setUserId(userId);
                            orgDeptUser.setOrgId(dto.getOrgId());
                            orgDeptUser.setDeptId(deptPostVO.getDeptId());
                            orgDeptUser.setIsDelete(SysUserConstants.N);
                            orgDeptUser.setCreateBy(SecurityUtils.getUsername());
                            orgDeptUser.setCreateTime(new Date());
                            orgDeptUsers.add(orgDeptUser);
                        }
                    }
                    // 新增用户-角色
                    if (StringUtils.isNotEmpty(dto.getRoleIds())) {
                        for (Long roleId : dto.getRoleIds()) {
                            SysUserRole userRole = new SysUserRole();
                            userRole.setOrgId(dto.getOrgId());
                            userRole.setIsDelete(SysUserConstants.N);
                            userRole.setUserId(userId);
                            userRole.setRoleId(roleId);
                            userRole.setCreateBy(SecurityUtils.getUsername());
                            userRole.setCreateTime(new Date());
                            sysUserRoles.add(userRole);
                        }
                    }
                }
            }

            if (CollectionUtil.isNotEmpty(orgDeptUsers)) {
                orgDeptUserMapper.batchOrgDept(orgDeptUsers);
            }
            if (CollectionUtil.isNotEmpty(sysUserRoles)) {
                userRoleMapper.batchUserRole(sysUserRoles);
            }
        }

        return rows;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int editOrg(SysUserDTO user) {
        List<SysUserRole> sysUserRoles = new ArrayList<>();
        List<SysOrgDeptUser> orgDeptUsers = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(user.getUserIds())) {
            for (Long userId : user.getUserIds()) {
                // 删除该用户下组织信息
                orgDeptUserMapper.deleteSysOrgDeptUserByUserId(userId);
                // 删除该用户下角色信息
                userRoleMapper.deleteUserRoleByUserId(userId);
                if (CollectionUtil.isNotEmpty(user.getInfoList())) {
                    for (SysUserInfoDTO dto : user.getInfoList()) {
                        // 判断是否默认组织
                        if (StringUtils.isNotEmpty(dto.getIsDefault()) && SysUserConstants.Y.equals(dto.getIsDefault())) {
                            // 更新用户主表默认组织信息
                            SysUser sysUser = new SysUser();
                            sysUser.setUserId(userId);
                            sysUser.setOrgId(dto.getOrgId());
                            sysUser.setUpdateBy(SecurityUtils.getUsername());
                            sysUser.setUpdateTime(DateUtils.getNowDate());
                            userMapper.updateUser(sysUser);
                        }
                        if (CollectionUtil.isNotEmpty(dto.getDeptPostList())) {
                            for (SysDeptPostVO deptPostVO : dto.getDeptPostList()) {
                                // 新增用户组织-部门-岗位
                                if (ObjectUtil.isNotEmpty(deptPostVO.getPostIds())) {
                                    for (Long postId : deptPostVO.getPostIds()) {
                                        SysOrgDeptUser orgDeptUser = new SysOrgDeptUser();
                                        orgDeptUser.setUserId(userId);
                                        orgDeptUser.setOrgId(dto.getOrgId());
                                        orgDeptUser.setDeptId(deptPostVO.getDeptId());
                                        orgDeptUser.setPostId(postId);
                                        orgDeptUser.setIsDelete(SysUserConstants.N);
                                        orgDeptUser.setCreateBy(SecurityUtils.getUsername());
                                        orgDeptUser.setCreateTime(new Date());
                                        orgDeptUsers.add(orgDeptUser);


                                    }
                                } else {
                                    SysOrgDeptUser orgDeptUser = new SysOrgDeptUser();
                                    orgDeptUser.setUserId(userId);
                                    orgDeptUser.setOrgId(dto.getOrgId());
                                    orgDeptUser.setDeptId(deptPostVO.getDeptId());
                                    orgDeptUser.setIsDelete(SysUserConstants.N);
                                    orgDeptUser.setCreateBy(SecurityUtils.getUsername());
                                    orgDeptUser.setCreateTime(new Date());
                                    orgDeptUsers.add(orgDeptUser);
                                }

                            }
                        }
                        // 新增用户-角色
                        if (StringUtils.isNotEmpty(dto.getRoleIds())) {
                            for (Long roleId : dto.getRoleIds()) {
                                SysUserRole userRole = new SysUserRole();
                                userRole.setOrgId(dto.getOrgId());
                                userRole.setIsDelete(SysUserConstants.N);
                                userRole.setUserId(userId);
                                userRole.setRoleId(roleId);
                                userRole.setCreateBy(SecurityUtils.getUsername());
                                userRole.setCreateTime(new Date());
                                sysUserRoles.add(userRole);
                            }
                        }
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(orgDeptUsers)) {
                orgDeptUserMapper.batchOrgDept(orgDeptUsers);
            }
            if (CollectionUtil.isNotEmpty(sysUserRoles)) {
                userRoleMapper.batchUserRole(sysUserRoles);
            }
        }
        return 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int editOrgUser(SysUserDTO user) {
        int rows = userMapper.updateUser(user);
        if (rows > 0) {
            Long userId = user.getUserId();
            List<SysUserRole> sysUserRoles = new ArrayList<>();
            List<SysOrgDeptUser> orgDeptUsers = new ArrayList<>();
            // 删除改用户下组织信息
            orgDeptUserMapper.deleteSysOrgDeptUserByUserId(userId);
            // 删除改用户下角色信息
            userRoleMapper.deleteUserRoleByUserId(userId);
            if (CollectionUtil.isNotEmpty(user.getInfoList())) {
                for (SysUserInfoDTO dto : user.getInfoList()) {
                    // 判断是否默认组织
                    if (StringUtils.isNotEmpty(dto.getIsDefault()) && SysUserConstants.Y.equals(dto.getIsDefault())) {
                        // 更新用户主表默认组织信息
                        SysUser sysUser = new SysUser();
                        sysUser.setUserId(userId);
                        sysUser.setOrgId(dto.getOrgId());
                        sysUser.setUpdateBy(SecurityUtils.getUsername());
                        sysUser.setUpdateTime(DateUtils.getNowDate());
                        userMapper.updateUser(sysUser);
                    }
                    if (CollectionUtil.isNotEmpty(dto.getDeptPostList())) {
                        for (SysDeptPostVO deptPostVO : dto.getDeptPostList()) {
                            // 新增用户组织-部门-岗位
                            if (ObjectUtil.isNotEmpty(deptPostVO.getPostIds())) {
                                for (Long postId : deptPostVO.getPostIds()) {
                                    SysOrgDeptUser orgDeptUser = new SysOrgDeptUser();
                                    orgDeptUser.setUserId(userId);
                                    orgDeptUser.setOrgId(dto.getOrgId());
                                    orgDeptUser.setDeptId(deptPostVO.getDeptId());
                                    orgDeptUser.setPostId(postId);
                                    orgDeptUser.setIsDelete(SysUserConstants.N);
                                    orgDeptUser.setCreateBy(SecurityUtils.getUsername());
                                    orgDeptUser.setCreateTime(new Date());
                                    orgDeptUsers.add(orgDeptUser);


                                }
                            } else {
                                SysOrgDeptUser orgDeptUser = new SysOrgDeptUser();
                                orgDeptUser.setUserId(userId);
                                orgDeptUser.setOrgId(dto.getOrgId());
                                orgDeptUser.setDeptId(deptPostVO.getDeptId());
                                orgDeptUser.setIsDelete(SysUserConstants.N);
                                orgDeptUser.setCreateBy(SecurityUtils.getUsername());
                                orgDeptUser.setCreateTime(new Date());
                                orgDeptUsers.add(orgDeptUser);
                            }

                        }
                    }
                    // 新增用户-角色
                    for (Long roleId : dto.getRoleIds()) {
                        SysUserRole userRole = new SysUserRole();
                        userRole.setOrgId(dto.getOrgId());
                        userRole.setIsDelete(SysUserConstants.N);
                        userRole.setUserId(userId);
                        userRole.setRoleId(roleId);
                        userRole.setCreateBy(SecurityUtils.getUsername());
                        userRole.setCreateTime(new Date());
                        sysUserRoles.add(userRole);
                    }
                }
            }

            if (CollectionUtil.isNotEmpty(orgDeptUsers)) {
                orgDeptUserMapper.batchOrgDept(orgDeptUsers);
            }
            if (CollectionUtil.isNotEmpty(sysUserRoles)) {
                userRoleMapper.batchUserRole(sysUserRoles);
            }
        }

        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int setGraded(SysUserDTO user) {
        List<SysOrganizationAdministrator> administratorList = new ArrayList<>();
        List<SysUserRole> sysUserRoleList = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(user.getUserIds())) {
            SysOrganizationAdministrator query = new SysOrganizationAdministrator();
            query.setUserIds(Arrays.asList(user.getUserIds()));
            query.setCode(UserManagerEnum.GRADED_ADMINISTRATOR.name());
            List<SysOrganizationAdministrator> administrators = administratorMapper.selectSysOrganizationAdministratorList(query);
            Map<Long, List<Long>> userOrgMap = administrators.stream()
                    .collect(Collectors.groupingBy(
                            SysOrganizationAdministrator::getUserId,
                            Collectors.mapping(SysOrganizationAdministrator::getOrgId, Collectors.toList())
                    ));
            for (Long userId : user.getUserIds()) {
                for (SysUserInfoDTO infoDTO : user.getInfoList()) {
                    // 已有组织的分级管理员不处理
                    if (!userOrgMap.containsKey(userId) || !userOrgMap.get(userId).contains(infoDTO.getOrgId())) {
                        SysOrganizationAdministrator administratorUser = administratorMapper.selectSysOrganizationAdministratorByUserId(userId, infoDTO.getOrgId());
                        if (ObjectUtil.isEmpty(administratorUser)) {
                            SysOrganizationAdministrator administrator = new SysOrganizationAdministrator();
                            administrator.setUserId(userId);
                            administrator.setOrgId(infoDTO.getOrgId());
                            administrator.setCode(UserManagerEnum.GRADED_ADMINISTRATOR.name());
                            administrator.setName(UserManagerEnum.GRADED_ADMINISTRATOR.getDesc());
                            administrator.setIsDelete(SysUserConstants.N);
                            administrator.setCreateBy(SecurityUtils.getUsername());
                            administrator.setCreateTime(new Date());
                            administratorList.add(administrator);
                        }
                        // 配置用户-角色关联关系
                        SysUserRole userRole = new SysUserRole();
                        userRole.setOrgId(infoDTO.getOrgId());
                        userRole.setUserId(userId);
                        userRole.setRoleId(infoDTO.getGradedRoleId());
                        SysUserRole sysUserRole = userRoleMapper.selectSysUserRoleList(userRole);
                        if (ObjectUtil.isEmpty(sysUserRole)) {
                            userRole.setIsDelete(SysUserConstants.N);
                            userRole.setCreateBy(SecurityUtils.getUsername());
                            userRole.setCreateTime(DateUtils.getNowDate());
                            sysUserRoleList.add(userRole);
                        }
                    }
                }
            }
        }
        // 插入管理员表
        if (CollectionUtil.isNotEmpty(administratorList)) {
            administratorMapper.batchInsert(administratorList);
        }
        // 插入用户-角色表
        if (CollectionUtil.isNotEmpty(sysUserRoleList)) {
            userRoleMapper.batchUserRoleOrg(sysUserRoleList);

        }
        return 1;
    }

    @Override
    public List<SysUserPremVO> previewPerm(Long userId, Long orgId) {
        List<SysUserPremVO> premVOS = new ArrayList<>();

        // 查询用户对应的角色权限列表
        Map<String, List<SysRoleMenuValue>> roleMap = new HashMap<>();
        List<SysRoleMenuValue> roleMenuValueList = roleMapper.getRoleValue(userId, orgId);
        if (CollectionUtil.isNotEmpty(roleMenuValueList)) {
            roleMap = roleMenuValueList.stream().collect(Collectors.groupingBy(item -> item.getRoleId() + "-" + item.getAppSceneId()));
        }
        // 查询用户对应的功能
        List<SysUserRoleMenuVO> roleMenuVOS = roleMapper.previewPerm(userId, orgId);
        if (CollectionUtil.isNotEmpty(roleMenuVOS)) {
            //根据角色id赋值权限列表
            for (SysUserRoleMenuVO roleMenuVO : roleMenuVOS) {
                SysUserPremVO userPremVO = new SysUserPremVO();
                userPremVO.setMenuId(roleMenuVO.getMenuId());
                userPremVO.setMenuName(roleMenuVO.getMenuName());
                userPremVO.setParentId(roleMenuVO.getParentId());
                List<SysRoleMenuValue> values = roleMap.get(roleMenuVO.getRoleId() + "-" + roleMenuVO.getAppSceneId());
                if (ObjectUtils.isNotEmpty(values)) {
                    userPremVO.setValues(values);
                }
                premVOS.add(userPremVO);
            }
            // 构建树结构
            premVOS = buildTree(premVOS);
        }
        return premVOS;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    public List<SysUserPremVO> buildTree(List<SysUserPremVO> menus) {
        List<SysUserPremVO> returnList = new ArrayList<SysUserPremVO>();
        List<Long> tempList = menus.stream().map(SysUserPremVO::getMenuId).collect(Collectors.toList());
        for (Iterator<SysUserPremVO> iterator = menus.iterator(); iterator.hasNext(); ) {
            SysUserPremVO menu = (SysUserPremVO) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<SysUserPremVO> list, SysUserPremVO t) {
        // 得到子节点列表
        List<SysUserPremVO> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysUserPremVO tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysUserPremVO> list, SysUserPremVO t) {
        return getChildList(list, t).size() > 0;
    }


    /**
     * 得到子节点列表
     */
    private List<SysUserPremVO> getChildList(List<SysUserPremVO> list, SysUserPremVO t) {
        List<SysUserPremVO> tlist = new ArrayList<SysUserPremVO>();
        Iterator<SysUserPremVO> it = list.iterator();
        while (it.hasNext()) {
            SysUserPremVO n = (SysUserPremVO) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }


    private void setDefaultDept(UserVo user) {
        if (!CollectionUtils.isEmpty(user.getUserDepts())) {
            for (UserDeptVo deptVo : user.getUserDepts()) {
                if ("Y".equals(deptVo.getIsDefault())) {
                    user.setDeptId(deptVo.getDeptId());
                    break;
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUserVo(UserVo user) {
        //默认组织赋值
//        setDefaultDept(user);
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        //新增用户组织关联
//        insertUserDeptVo(user);
//        //新增用户机场关联
//        insertUserAirportVo(user);
//        // 新增用户岗位关联
//        insertUserPostVo(user);
//        // 新增用户与角色管理
//        insertUserRoleVo(user);
        return rows;
    }

    public void insertUserDeptVo(UserVo user) {
        List<UserDeptVo> userDepts = user.getUserDepts();
        if (userDepts != null) {
            List<SysUserDept> list = new ArrayList<SysUserDept>();
            for (UserDeptVo vo : userDepts) {
                SysUserDept sysUserDept = new SysUserDept();
                sysUserDept.setUserId(user.getUserId());
                sysUserDept.setDeptId(vo.getDeptId());
                sysUserDept.setIsDefault(vo.getIsDefault());
                sysUserDept.setUserDeptType(vo.getUserDeptType());
                sysUserDept.setUserDeptTypeRefCode(vo.getUserDeptTypeRefCode());
                list.add(sysUserDept);
            }
            if (list != null && list.size() > 0) {
                userDeptMapper.batchUserDept(list);
            }
        }
    }

    public void insertUserAirportVo(UserVo user) {
        List<UserDeptVo> userDepts = user.getUserDepts();
        if (userDepts != null) {
            List<SysUserAirport> list = new ArrayList<SysUserAirport>();
            for (UserDeptVo vo : userDepts) {
                String[] airportCodes = vo.getAirportCodes();
                if (StringUtils.isNotEmpty(airportCodes)) {
                    for (String airportCode : airportCodes) {
                        SysUserAirport sysUserAirport = new SysUserAirport();
                        sysUserAirport.setUserId(user.getUserId());
                        sysUserAirport.setDeptId(vo.getDeptId());
                        sysUserAirport.setAirportCode(airportCode);
                        list.add(sysUserAirport);
                    }
                }
            }
            if (list != null && list.size() > 0) {
                userAirportMapper.batchUserAirport(list);
            }
        }
    }


    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUser user) {

        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return userMapper.updateUser(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserVo(UserVo userVo) {
//        setDefaultDept(userVo);
//        Long userId = userVo.getUserId();
//        //删除用户组织关联
//        userDeptMapper.deleteSysUserDeptByUserId(userId);
//        //新增用户组织关联
//        insertUserDeptVo(userVo);
//        //删除用户机场关联
//        userAirportMapper.deleteSysUserAirportByUserId(userId);
//        //新增用户机场关联
//        insertUserAirportVo(userVo);
//
//        // 删除用户与角色关联
//        userRoleMapper.deleteUserRoleByUserId(userId);
//        // 新增用户与角色管理
//        insertUserRoleVo(userVo);
//        // 删除用户与岗位关联
//        userPostMapper.deleteUserPostByUserId(userId);
//        // 新增用户与岗位管理
//        insertUserPostVo(userVo);
        return userMapper.updateUser(userVo);
    }

    @Override
    public int updateUserInfo(UserVo user) {
        return userMapper.updateUser(user);
    }

    @Override
    public int updateUserOrg(UserVo user) {
        return 0;
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }


    public void insertUserRoleVo(UserVo userVo) {
        List<UserDeptVo> userDepts = userVo.getUserDepts();
        if (userDepts != null) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (UserDeptVo vo : userDepts) {
                Long[] roleIds = vo.getRoleIds();
                if (StringUtils.isNotEmpty(roleIds)) {
                    for (Long roleId : roleIds) {
                        SysUserRole ur = new SysUserRole();
                        ur.setUserId(userVo.getUserId());
                        ur.setRoleId(roleId);
                        ur.setDeptId(vo.getDeptId());
                        list.add(ur);
                    }
                }
            }
            if (list != null && list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    public void insertUserPostVo(UserVo userVo) {
        List<UserDeptVo> userDepts = userVo.getUserDepts();
        if (userDepts != null) {
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (UserDeptVo vo : userDepts) {
                Long[] posts = vo.getPostIds();
                if (StringUtils.isNotEmpty(posts)) {
                    for (Long postId : posts) {
                        SysUserPost up = new SysUserPost();
                        up.setUserId(userVo.getUserId());
                        up.setPostId(postId);
                        up.setDeptId(vo.getDeptId());
                        list.add(up);
                    }
                }
            }
            if (list != null && list.size() > 0) {
                userPostMapper.batchUserPost(list);
            }
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        //删除用户组织关联
        userDeptMapper.deleteSysUserDeptByUserIds(userIds);
        //删除用户机场关联
        userAirportMapper.deleteSysUserAirportByUserIds(userIds);
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
//        String password = configService.selectConfigByKey("sys.user.initPassword");
        String password = "123456";
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(user);
                    checkUserDataScope(user.getUserId());
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public Boolean addIp(Long userId, String loginIp) {
        return userMapper.addIp(userId, loginIp);
    }

    /**
     * 微信小程序-用户绑定openId
     *
     * @param openId
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int userBindOpenId(String openId, Long userId) {
        return userMapper.userBindOpenId(openId, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUserOfWeCat(UserVo userVo) {
        List<UserDeptVo> userDepts = new ArrayList<>();
        UserDeptVo userDeptVo = new UserDeptVo();
        userDepts.add(userDeptVo);
        //获取角色id
        List<Long> roles = roleMapper.selectRoleListByRoleName("散货主");
        if (!CollectionUtils.isEmpty(roles)) {
            userDeptVo.setRoleIds(new Long[]{roles.get(0)});
        }
        //获取部门id
        List<Long> depts = userdeptMapper.selectDeptListBydeptName("散货主");
        if (!CollectionUtils.isEmpty(depts)) {
            userDeptVo.setDeptId(depts.get(0));
        }
        //获取本系统所有航点信息
        DicAirportLocal dicAirportLocal = new DicAirportLocal();
        dicAirportLocal.setIsDelete("0");
        R<List<DicAirportLocal>> airportLocalList = remoteBasicdataService.getAirportLocalList(dicAirportLocal,
                SecurityConstants.INNER);
        if (R.SUCCESS != airportLocalList.getCode()) {
            throw new ServiceException(airportLocalList.getCode() + airportLocalList.getMsg());
        }
        if (!CollectionUtils.isEmpty(airportLocalList.getData())) {
            userDeptVo.setAirportCodes(airportLocalList.getData().stream()
                    .map(DicAirportLocal::getAirportCode).toArray(String[]::new));
        }
        userDeptVo.setUserDeptType("airPersonal");//散货主
        userDeptVo.setIsDefault("Y");
        userVo.setUserDepts(userDepts);
        return this.insertUserVo(userVo);
    }

    @Override
    public LoginUser selectByOpenId(String openId) {
        SysUser sysUser = userMapper.selectByOpenId(openId);
        if (sysUser == null) {
            return null;
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);

    /*    SysUserDeptQuery sysUserDept = new SysUserDeptQuery();
        sysUserDept.setUserId(sysUser.getUserId());
        sysUserDept.setDeptId(sysUser.getDeptId());
        List<SysUserDept> sysUserDeptList = sysUserDeptService.selectSysUserDeptList(sysUserDept);*/
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        sysUserVo.setModifyPwdTime(sysUser.getModifyPwdTime());
        /*sysUserVo.setLoginDeptId(sysUser.getDeptId());
        if (sysUserDeptList != null && sysUserDeptList.size() > 0) {
            String userDeptType = sysUserDeptList.get(0).getUserDeptType();
            if (AIR_PERSONAL_CODE.equals(userDeptType) || AIRLINE_CODE.equals(userDeptType)) {
                sysUserVo = null;
            } else {
                sysUserVo.setLoginUserDeptType(userDeptType);
                sysUserVo.setLoginUserTypeFefCode(sysUserDeptList.get(0).getUserDeptTypeRefCode());
            }
        }*/
        //获取用户类型
        SysOrganization organization = sysOrganizationMapper.selectSysOrganizationByOrgId(sysUser.getOrgId());
        if (StringUtils.isNotNull(organization)) {
            if (StringUtils.isNotEmpty(organization.getLoginUserDeptType())) {
                sysUserVo.setLoginUserDeptType(organization.getLoginUserDeptType());
            }
            if (StringUtils.isNotEmpty(organization.getLoginUserTypeFefCode())) {
                sysUserVo.setLoginUserTypeFefCode(organization.getLoginUserTypeFefCode());
            }
        }
        List<SysOrganization> organizationList = permissionService.getOrgIdPermission(sysUser);
        Set<Long> orgIds = organizationList.stream().map(SysOrganization::getOrgId).collect(Collectors.toSet());
        sysUserVo.setOrgIds(orgIds);
        sysUserVo.setOrgId(sysUser.getOrgId());
        return sysUserVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int userUnBindOpenId(Long userId) {
        return userMapper.userUnBindOpenId(userId);
    }

    @Override
    public List<LeaderInfoVO> queryUserListForPlan(String queryStr) {
        return userMapper.queryUserListForPlan(queryStr);
    }

    @Override
    public List<SysUser> selectAllSysUser(SysUser sysUser) {
        return userMapper.selectAllSysUser(sysUser);
    }

    @Override
    public void unLockUser(UnlockUserVO unlockUserVO) {
        // 只有管理员才有权限解锁，检查是否管理员身份
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null || !SecurityUtils.isAdmin(loginUser.getUserid())) {
            throw new RuntimeException("当前登录用户不是管理员,无权限解锁用户,请联系管理员");
        }
        // 解锁用户锁定状态
        SysUser sysUser = userMapper.selectUserById(unlockUserVO.getUserId());
        if (Objects.isNull(sysUser)) {
            throw new RuntimeException(String.format("该用户不存在,userId:%s", unlockUserVO.getUserId()));
        }
        clearLoginRecordCache(sysUser.getUserName());
    }

    public void clearLoginRecordCache(String loginName) {
        if (redisService.hasKey(getCacheKey(loginName))) {
            redisService.deleteObject(getCacheKey(loginName));
        }
    }

    /**
     * 登录账户密码错误次数缓存键名
     *
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username) {
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }

    /**
     * 判断用户是否被锁定
     *
     * @param userName 用户名
     * @return 是否被锁定
     */
    private boolean isLockUser(String userName) {
        Integer retryCount = redisService.getCacheObject(getCacheKey(userName));
        if (retryCount == null) {
            retryCount = 0;
        }
        return retryCount >= CacheConstants.PASSWORD_MAX_RETRY_COUNT;
    }

    @Override
    public List<SysUser> selectUserInfoByUserNames(String[] usernames) {
        return userMapper.selectUserInfoByUserNames(usernames);
    }

    @Override
    public List<SysUser> selectUserInfoByUserIds(Long[] userIds) {
        return userMapper.selectUserInfoByUserIds(userIds);
    }

    @Override
    public List<SysUserOrgInfoVO> getUserOrgInfo(Long userId) {
        List<SysUserOrgInfoVO> userOrgInfoVOS = new ArrayList<>();
        // 获取用户组织关联关系-按照分组
        List<SysOrgDeptUserVO> orgUsers = sysOrgDeptUserMapper.selectUserOrgByUserId(userId);
        // 获取用户全部详情-包含组织，部门，岗位
        // 按照组织分组
        if (CollectionUtil.isNotEmpty(orgUsers)) {
            // 获取组织
            for (SysOrgDeptUserVO userVO : orgUsers) {
                List<SysDeptPostVO> deptPostVOS = new ArrayList<>();
                // 获取用户岗位列表
                Map<Long, List<SysOrgDeptUserVO>> postMap = new HashMap<>();
                SysOrgDeptUserVO userPostQuery = new SysOrgDeptUserVO();
                userPostQuery.setIsDelete(SysUserConstants.N);
                userPostQuery.setUserId(userId);
                userPostQuery.setOrgId(userVO.getOrgId());
                List<SysOrgDeptUserVO> userPostList = sysOrgDeptUserMapper.selectUserPostByVO(userPostQuery);
                if (CollectionUtil.isNotEmpty(userPostList)) {
                    postMap = userPostList.stream().collect(Collectors.groupingBy(SysOrgDeptUserVO::getDeptId));
                }
                SysUserOrgInfoVO infoVO = new SysUserOrgInfoVO();
                infoVO.setOrgId(userVO.getOrgId());
                infoVO.setOrgName(userVO.getOrgName());
                infoVO.setIsDefault(userVO.getIsDefault());
                // 获取用户部门列表
                SysOrgDeptUserVO userDeptQuery = new SysOrgDeptUserVO();
                userDeptQuery.setIsDelete(SysUserConstants.N);
                userDeptQuery.setUserId(userId);
                userDeptQuery.setOrgId(userVO.getOrgId());
                List<SysOrgDeptUserVO> userDeptList = sysOrgDeptUserMapper.selectUserDeptByVO(userDeptQuery);
                if (CollectionUtil.isNotEmpty(userDeptList)) {
                    for (SysOrgDeptUserVO deptUserVO : userDeptList) {
                        SysDeptPostVO deptPostVO = new SysDeptPostVO();
                        deptPostVO.setDeptId(deptUserVO.getDeptId());
                        List<SysOrgDeptUserVO> postInfo = postMap.get(deptUserVO.getDeptId());
                        if (CollectionUtil.isNotEmpty(postInfo)) {
                            deptPostVO.setPostIds(postInfo.stream().map(SysOrgDeptUserVO::getPostId).toArray(Long[]::new));
                        }
                        deptPostVOS.add(deptPostVO);
                    }
                }
                infoVO.setDeptPostList(deptPostVOS);
                // 获取用户角色列表
                List<SysUserRole> roleList = userRoleMapper.selectSysUserRoleByOrg(userId, userVO.getOrgId());
                if (CollectionUtil.isNotEmpty(roleList)) {
                    infoVO.setRoleIds(roleList.stream().map(SysUserRole::getRoleId).toArray(Long[]::new));
                }
                userOrgInfoVOS.add(infoVO);
            }
        }
        return userOrgInfoVOS;
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param vo 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<UserVo> selectAllUserList(UserVo vo) {
        Long orgId = SecurityUtils.getLoginUser().getOrgId();
        Long loginUserId = SecurityUtils.getLoginUser().getUserid();
        vo.setOrgId(orgId);
        List<UserVo> sysUsers = userMapper.selectAllUserList(vo);
        for (UserVo model : sysUsers) {
            if (loginUserId.equals(model.getUserId())) {
                model.setCrossOrg("OWN");
            } else {
                List<SysOrgDeptUserVO> orgDeptUserVOList = orgDeptUserMapper.selectUserOrgByUserId(model.getUserId());
                if (isCrossOrg(orgDeptUserVOList, orgId)) {
                    model.setCrossOrg("YES");
                } else {
                    model.setCrossOrg("NO");
                }
            }
        }
        return sysUsers;
    }

    public boolean isCrossOrg(List<SysOrgDeptUserVO> orgDeptUserVOList, Long orgId) {
        boolean flag = false;
        for (SysOrgDeptUserVO sysOrgDeptUser : orgDeptUserVOList) {
            if (orgId.equals(sysOrgDeptUser.getOrgId())) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    @Override
    public int bindUserRole(SysRoleBindVO dto) {
        int rows = 0;
        if (ObjectUtil.isNotEmpty(dto.getUserIds())) {
            List<SysUserRole> userRoleList = new ArrayList<>();
            for (Long userId : dto.getUserIds()) {
                SysUserRole userRole = new SysUserRole();
                userRole.setRoleId(dto.getRoleId());
                userRole.setUserId(userId);
                userRole.setOrgId(dto.getOrgId());
                userRole.setCreateBy(SecurityUtils.getUsername());
                userRole.setCreateTime(DateUtils.getNowDate());
                userRoleList.add(userRole);
            }
            userRoleMapper.batchUserRoleOrg(userRoleList);
            rows++;
        }
        return rows;
    }

    @Override
    public List<SysRole> getRoleByOrg(Long orgId) {
        return roleMapper.selectRoleByOrg(orgId);
    }

    @Override
    public List<String> exchangeUserIdBySubject(UserSubjectDTO userSubjectDTO) {
        if (!"ROLE,USER,DEPT,POST".contains(userSubjectDTO.getSubject())) {
            throw new ServiceException("用户体系主体类型不存在,不是【ROLE,USER,DEPT,POST】其中之一");
        }
        if (CollectionUtil.isEmpty(userSubjectDTO.getSubjectValues())) {
            throw new ServiceException("用户体系主体数据不能为空");
        }
        return sysUserMapper.selectUserIdBySubject(userSubjectDTO);
    }

    @Override
    public List<String> getUserRoleFunction(GetUserRoleFunctionRequest request) {
        SysModelRoleFunction query = new SysModelRoleFunction();
        query.setUserId(request.getUserId());
        List<SysModelRoleFunction> functions = sysModelRoleFunctionService.selectSysModelRoleFunctionList(query);
        return functions.stream().map(SysModelRoleFunction::getRoleFunction).distinct().collect(Collectors.toList());
    }

    private void setDeptIds(SysUser sysUser) {
        List<SysOrganizationDeptDTO> sysOrganizationDeptList = sysOrganizationDeptMapper.selectSysOrganizationDeptListByUserId(sysUser.getUserId());
        List<Long> deptIds = sysOrganizationDeptList.stream().map(SysOrganizationDeptDTO::getDeptId).distinct().collect(Collectors.toList());
        sysUser.setDeptIds(deptIds);
    }

}
